﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DemoPlayer : MonoBehaviour {
    public GameObject centerBase;
    public float sx = 0.1f;
    public float sy = 0.1f;
    public float zOff = 10;

    public GameObject bullet;

    void Start()
    {
        centerBase = DemoCamera.Instance.centerObj;
    }
    void FixInCamera()
    {
        var cam = DemoCamera.Instance;
        var ppos = transform.position;
        var cc = cam.GetComponent<Camera>();
        var pos = cc.WorldToViewportPoint(ppos);
        pos.x = Mathf.Clamp01(pos.x);
        pos.y = Mathf.Clamp01(pos.y);
        transform.position = cc.ViewportToWorldPoint(pos);
    }

    void MovePlayer()
    {
        var iv = DemoControl.Instance.inputValue;
        var cam = DemoCamera.Instance;
        var cc = cam.GetComponent<Camera>();

        var ppos = transform.position;
        var pos = cc.WorldToViewportPoint(ppos);
        pos.x += iv.x * Time.deltaTime * sx;
        pos.y += iv.y * Time.deltaTime * sy;

        pos.x = Mathf.Clamp01(pos.x);
        pos.y = Mathf.Clamp01(pos.y);

        pos.z = zOff;
        transform.position = cc.ViewportToWorldPoint(pos);
    }
    void SetDir()
    {
        var cam = DemoCamera.Instance;
        transform.rotation = cam.transform.rotation;
    }

    void AdjustZ()
    {
        var iv = DemoControl.Instance.inputValue;
        var cam = DemoCamera.Instance;
        var cc = cam.GetComponent<Camera>();

        var ppos = transform.position;
        var pos = cc.WorldToViewportPoint(ppos);
        pos.z = zOff;
        transform.position = cc.ViewportToWorldPoint(pos);
    }

    private float lastShoot = 0;
    void Shoot()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (Time.time - lastShoot > 0.1f)
            {
                lastShoot = Time.time;
                var b = GameObject.Instantiate<GameObject>(bullet);
                b.transform.position = transform.position;
                b.SetActive(true);
            }
        }
    }

    void Update()
    {
        AdjustZ();
        MovePlayer();
        SetDir();

        Shoot();
    }

}
